<script>
	import {mapState,mapMutations} from 'vuex'
	import config from '@/config/config'
	import wechat from 'static/wechat.js'
	
	export default {
		globalData: {  
			whiteList:['/pages/greet','/pages/login/login','/pages/login/reg','/pages/login/pwd','/']
		},
		computed: {
			...mapState(['forcedLogin', 'hasLogin','userInfo','newMsgNum']),
			// 登陆 状态
			loginStatus(){ return this.$store.state.loginStatus; },
			// 路由
			path:function(){
				let pages = (getCurrentPages && getCurrentPages()) || [];
				let currentPage = pages[pages.length - 1];
				let url = currentPage ? `/${currentPage.route}` : (getCurrentPages ? '/' : '');
				return (this.$route && this.$route.path) || url || '';
			}
		},
		onLaunch: function() {
			//验证token
			if(this.isStartupValidToken!=true){
				this.resetLoginLogic('onLaunch');
			}
			//this.csdWebSocket();
			
			//微信小程序-检测更新
			// #ifdef MP-WEIXIN  
				this.wxUpdateManager();
			// #endif
		},
		onShow: function() {
			//验证token
			if(this.isStartupValidToken!=true){
				this.resetLoginLogic('onShow');
			}else{
				this.isStartupValidToken = false;
			}
			//  获取地址
			this.getLocation();
		},
		onHide: function() {
			
		},
		watch:{ 
			// 全局路由
			"$route.path":function(){
				this.resetLoginLogic('$route.path');
				// if(this.newMsgNum > 0){
				// 	uni.showTabBarRedDot({index:2});
				// }else{
				// 	uni.hideTabBarRedDot({index:2});
				// }
			},
			// 登陆状态
			loginStatus:function(newVal){
				this.resetLoginLogic('loginStatus');
			},
			// 新消息
			newMsgNum:function(newVal){
				// if(newVal > 0){
				// 	uni.showTabBarRedDot({index:2});
				// }else{
				// 	uni.hideTabBarRedDot({index:2});
				// }
			}
		},
		methods: {
			...mapMutations(['login','logout','setUserInfo','autoModeLogin','setCsdMsgChatList',"setUserAddrInfo"]),
			//检测更新
			wxUpdateManager: function() {
				const updateManager = uni.getUpdateManager();
				updateManager.onUpdateReady(function(res) {
					uni.showModal({
						title: '更新提示',
						content: '发现新版本，是否重启应用？',
						success(res) {
							if (res.confirm) {
								//新的版本已经下载好， 调用 applyUpdate 应用新版本并重启
								updateManager.applyUpdate();
							}
						}
					});
				});
				// 新的版本下载失败
				updateManager.onUpdateFailed(function(res) {  });
			},
			// 重置登录逻辑
			resetLoginLogic: function(type){
				//重置变量
				if(type == 'onLaunch') this.isStartupValidToken = true;
				//  ------已登录----------
				if(this.hasLogin === true || uni.getStorageSync('access_token')){
					if(this.path=='/' && type !=='loginStatus' ) return false;
					if(type!='$route.path') this.validToken();	
					return false;
				}
				//--------不需要登录------
				if(!this.forcedLogin){ return false; }
				// --------未登录 ----------
				//白名单不需要登录
				if(this.$options.globalData.whiteList.indexOf(this.path)!= -1 && type!=='loginStatus'){
					return false;
				}
				
				//wx-web 微信公众号登录模式
				if( config.webMode == 'wx-web' && window && window.WeixinJSBridge){
					//这个可以关闭安卓系统的手机
					document.addEventListener('WeixinJSBridgeReady', function(){
						WeixinJSBridge.call('closeWindow'); 
					}, false);
					//这个可以关闭ios系统的手机
					WeixinJSBridge.call('closeWindow');
					return false;				
				}
				
				uni.reLaunch({ url: '/pages/login/login'});
			},
			//验证token
			validToken: function() {
				if( uni.getStorageSync('access_token') ) {
					this.$request("/app/soft/Authorization/checToken",{}).then((res)=>{
						if(res.data && res.data.userinfo){
							this.setUserInfo(res.data.userinfo);
						}
						if(this.$options.globalData.whiteList.indexOf(this.path)!=-1){
							uni.switchTab({ url: '/pages/main/main'});
						}
					}).catch((e)=>{
						this.logout();
					});
				} else {
					this.logout();
				}
			},
			// 获取地址
			getLocation(){
				if(this.forcedLogin && !this.hasLogin && config.webMode == 'wx-web'){
					return false;
				}
				wechat.getLocation(res=>{
					this.setUserAddrInfo(res.data);
				},true);
			},
			// 点击导航
			onTabItemTap(e){
			
			},
			// Web Socket 连接
			csdWebSocket(){
				let that = this;
				let user_guid = that.userInfo.user_guid;
				if(!user_guid || !this.hasLogin) {
					setTimeout(function(){ 
						that.csdWebSocket();
					},1000);
					return false;
				}
				uni.connectSocket({ url: config.webSocketUrl });
				uni.onSocketOpen(function (res) {
					let param = {data:JSON.stringify({type:"reg",mine:{id:user_guid}})}
					uni.sendSocketMessage(param);
				});
				uni.onSocketMessage(function (res) {
					var data = JSON.parse(res.data);
					if(data.type == 'getChatList'){
						_fn();
					}
				});
				uni.onSocketError(function (res) {
					console.log('WebSocket连接打开失败，请检查！');
				});
				function _fn(){
					that.$request("/common/app_csd/getChatList",{},false).then(res=>{
						let data = res.data;
						let chatList = (data || []).map(function(h){
							return {
								uid:h.user_guid,
								username:h.username,
								img: h.img,
								time:h.time,
								msg: h.content,
								tis_num:h.tis_num
							}
						});
						that.setCsdMsgChatList(chatList);
					});
				}
				_fn();
			}
		}
	}
</script>

<style lang="scss">
	/* uni.css - 通用组件、模板样式库，可以当作一套ui库应用 */
	@import './static/style/uni.css';
	@import './static/iconfont/iconfont.css';
	@import './static/style/app.scss';
	@import "/static/iconfont/font.scss";
</style>
<style>
	uni-toast{ z-index: 99999999999 !important; }
	.content .msg-list uni-image>img {
	   position: relative !important;
	   opacity: 1 !important;
	}
</style>	